import { uploadAct,getImg,rechargeHistory, releaseAct, addComment, getCommentList, deleteComment, commission, verifyInfo,goodsPay  } from '@/pages/api/index.js'
import { timingSafeEqual } from 'crypto';
export default {
  data() {
    return {
      test_img:'',
      imgData:{
        //  accept: 'image/gif, image/bmp, image/png, image/jpg',
         accept:['.gif','.bmp','.png','.jpg']
       },
       successList:'',     //上传成功
          removeList:'',      //移除时
      rules: {
        evaluateContent: [
          { required: true, message: '请输入指定评论', trigger: 'blur' },
        ],
      },
      dialogFormVisible: false,
      itemSpell: '',
      checked: true,
      checked1: true,
      checked2: false,
      dialogImageUrl: '',
      dialogVisible: false,
      value1: '',
      checkList: ['货比三家', '收藏浏览'],
      firstPage: true,      //第一个页面
      buyPage: false,       //支付页面
      maskLayer: false,     //遮罩层
      buySuccess: false,    //支付成功页面
      imageUrl: '',
      oneImgUrl:'',
      dataTable: {
        shopsId: this.$route.params.shopsId,       //店铺id
        babyGood: '',      //商品名称
        goodLink: '',      //商品链接
        goodPrice: '',     //商品单价
        babyId: '',        //宝贝id
        taskTime: '',      //活动日期
        imgLink: '',       //图片id
        evaluateIds: '',  //上传评论拼接所有id
        allBJ: 0,
        allYJ: 0,
        task: [{
          num: 0,              //本金
          yj: 0,              //佣金
          keyword: "",         //搜索关键词
          search1: 1,          //排序方式
          search2: 1,         //筛选方式
          value_added: ['1', 2],     //增值服务
          mold: 1,            //活动类型
          evaluate_content: {},//评价内容
          antistop: '',        //关键词淘口令
          coupon: '',     //优惠券淘口令
          coupon_money: '', //优惠券价格
          insurance: '',       //是否勾选保险
          insurancePrice: 0,    //保险价格
          evaluate_img: '',    // "多张图片用 ',' 逗号隔开 ，1,2,3",
          times: [{
            key: 7,
            value: '',
          }, {
            key: 8,
            value: '',
          }, {
            key: 9,
            value: '',
          }, {
            key: 10,
            value: '',
          }, {
            key: 11,
            value: '',
          }, {
            key: 12,
            value: '',
          }, {
            key: 13,
            value: '',
          }, {
            key: 14,
            value: '',
          }, {
            key: 15,
            value: '',
          }, {
            key: 16,
            value: '',
          }, {
            key: 17,
            value: '',
          }, {
            key: 18,
            value: '',
          }, {
            key: 19,
            value: '',
          }, {
            key: 20,
            value: '',
          }, {
            key: 21,
            value: '',
          }, {
            key: 22,
            value: '',
          }],
        }],
      },
      //添加评论的数据
      commentData: {
        evaluateContent: '',
        evaluateImg: '',
      },
      //获取评价数据
      getCommentList: [],
      // 多图上传将数组拼接到字符串中
      mulpArr: [],
      commentId: [],
      price: '',
      //佣金的接口
      getCom: {
        goodPrice: '',
        num: '',
      },
      //佣金
      yongjin: {
        num: '',
        goodPrice: '',
      },
      dataList: {},
      //总价格
      allPrice: 0,
      //总额
      //选择评价单的时候控制评价单的显示隐藏
      show: false,
      goodsId:0,
      imgData:{
        //  accept: 'image/gif, image/bmp, image/png, image/jpg',
         accept:['.gif','.bmp','.png','.jpg']
       },
       allImg:0,    //图片总数
    };
  },
  computed: {

  },
  watch: {
    //计算本金
    'dataTable.task': {

      handler(val) {
        this.ze()
        this.bj()
        this.yj()
        this.zd()
        this.infoShow()
        val.forEach((item, index) => {
          var sum = 0
          for (let key in item.times) {
            sum += +item.times[key]['value']
          }
          //根据mold来判断是原价单，评价单，还是优惠券单，然后计算对应的价格
          if (item.mold == 1) {
            item.num = sum * this.dataTable.goodPrice
            if (item.insurance) {
              item.insurancePrice = item.num / 100
            } else {
              item.insurancePrice = 0
            }
            this.yongjin = {
              num: sum,
              goodPrice: this.dataTable.goodPrice,
              mold: item.mold
            }
            commission(this.yongjin).then(res => {
              item.yj = res.data.commission
            })

          } else if (item.mold == 2) {
            item.num = sum * this.dataTable.goodPrice
            if (item.insurance) {
              item.insurancePrice = item.num / 100
            } else {
              item.insurancePrice = 0
            }
            this.yongjin = {
              num: sum,
              goodPrice: this.dataTable.goodPrice,
              mold: item.mold
            }
            commission(this.yongjin).then(res => {
              item.yj = res.data.commission
            })
          } else {
            item.num = sum * item.coupon_money
            if (item.insurance) {
              item.insurancePrice = item.num / 100
            } else {
              item.insurancePrice = 0
            }
            this.yongjin = {
              num: sum,
              goodPrice: item.coupon_money,
              mold: item.mold
            }
            commission(this.yongjin).then(res => {
              item.yj = res.data.commission

            })
          }
        })
      },
      deep: true
    },
    //计算佣金
    'dataTable.goodPrice': {
      handler(val) {
        this.ze()
        // this.yj()
        this.bj()
        this.dataTable.task.forEach((item, index) => {
          var sum = 0
          for (let key in item.times) {
            sum += +item.times[key]
          }
          //根据mold来判断是原价单，评价单，还是优惠券单，然后计算对应的价格
          if (item.mold == 1) {
            commission(this.yongjin).then(res => {
              item.yj = res.data.commission

            })
            item.num = sum * this.dataTable.goodPrice
            if (item.insurance) {
              item.insurancePrice = item.num / 100
            } else {
              item.insurancePrice = 0
            }
            this.yongjin = {
              num: sum,
              goodPrice: this.dataTable.goodPrice,
              mold: item.mold
            }

          } else if (item.mold == 2) {
            item.num = sum * this.dataTable.goodPrice
            if (item.insurance) {
              item.insurancePrice = item.num / 100
            } else {
              item.insurancePrice = 0
            }
            this.yongjin = {
              num: sum,
              goodPrice: this.dataTable.goodPrice,
              mold: item.mold
            }
            commission(this.yongjin).then(res => {
              item.yj = res.data.commission

            })
          } else {
            item.num = sum * item.coupon_money
            if (item.insurance) {
              item.insurancePrice = item.num / 100
            } else {
              item.insurancePrice = 0
            }
            this.yongjin = {
              num: sum,
              goodPrice: item.coupon_money,
              mold: item.mold
            }
            commission(this.yongjin).then(res => {
              item.yj = res.data.commission

            })
          }
        })
      },
      deep: true
    },
  },
  methods: {
    handleRemove(file, fileList) {
      this.removeList = file.response.data.id
      if(this.removeList !== '' && this.successList !== ''){
          this.removeList = ''
          this.successList = ''
      }
    },
    onSuccess(res,file,fileList){
      this.successList = res.data.id
    },
    handleExceed(files, fileList) {
      this.$message.warning('最多只能上传一张图片');
    },
    //限制图片格式 accept="image/gif,image/jpg,image/png,image/bmp"
    beforeAvatarUpload(file) {
      var fType = file.name.substr(file.name.lastIndexOf("."))
        let type = file.type
        if(this.imgData.accept.indexOf(fType) == -1){
            this.$message.warning('不能使用除了gif，bmp，png，jpg之外的格式')
            return false
        }
    },
    //文件超出个数限制时的钩子
    exceed(file, filelist) {
      this.$message({
        message: '最多只能上传一张图片',
        type: 'warning'
      })
    },
    exceedFive() {
      this.$message({
        message: '最多只能上传五张图片',
        type: 'warning'
      })
    },
    //限制图片格式 accept="image/gif,image/jpg,image/png,image/bmp"
       beforeAvatarUpload(file) {
        var fType = file.name.substr(file.name.lastIndexOf("."))
          let type = file.type
          if(this.imgData.accept.indexOf(fType) == -1){
              this.$message.warning('不能使用除了gif，bmp，png，jpg之外的格式')
              return false
          }
      },
    infoShow() {
      var count = 0
      this.dataTable.task.forEach((item, index) => {
        if (item.mold == 2) {
          count++
          if (count == 1) {
            this.show = true
          }
        } else if (item.mold !== 2 && count !== 1) {
          this.show = false
        }
      })
    },
    //总额
    ze() {
      var res = 0;
      var yj = 0;
      var insurancePrice = 0;
      this.dataTable.task.forEach(item => {
        res += +item.num
        yj += +item.yj
        insurancePrice += +item.insurancePrice
      })
      return (res + yj + insurancePrice).toFixed(2)
    },
    //本金
    bj() {
      var res = 0;
      this.dataTable.task.forEach(item => {
        res += +item.num
      })
      return res.toFixed(2)
    },
    //佣金
    yj() {
      var res = 0
      this.dataTable.task.forEach(item => {
        res += +item.yj
      })
      return res
    },
    //总单数
    zd() {
      var res = 0
      this.dataTable.task.forEach(item => {
        item.times.forEach((value, index) => {
          res += +value.value
        })
      })
      return res
    },
    //数据列表展示接口
    getList() {
      getCommentList({pageSize: "100", pageIndex: "1" }).then(res => {
        this.getCommentList = res.data
      })
    },
    //多图上传
    mulpitleUpload({ action, file }) {
      var formData = new FormData()
      formData.append('file', file)
      uploadAct(formData).then(res => {
        this.succ(res)
        if (res.code == 0) {
          this.$message({
            message: '上传图片成功',
            type: 'success'
          })
          addComment(this.commentData).then(res => {
            if (res.code == 0) {
              this.mulpArr = []
              this.commentData.evaluateImg = ''
              this.getList()
              this.$message({
                message: "添加评论成功",
                type: 'success'
              })
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }
          })
        } else {
          this.$message.error('上传图片失败')
        }
      })
    },

    succ(response, file, fileList) {
      this.mulpArr.push(response.data.id)
      this.commentData.evaluateImg = this.mulpArr.join()
    },
    remove(res, file, fileList) {
    },
    /**
     *
     * @param {*} param0
     * 提交图片的实现
     */
    submitFileUpload({ action, file }) {
      var formData = new FormData();
      formData.append('file', file);

      uploadAct(formData).then(res => {
        if (res.code == 0) {
          var reader = new FileReader();
          reader.readAsDataURL(file);
          this.test_img = reader.result;
          this.$message({
            message: '上传图片成功',
            type: 'success'
          })
          this.dataTable.imgLink = res.data.id
        } else {
          this.$message.error('上传图片失败');
        }
      })
    },
    /* 增加数据 */
    addData() {
      this.dataTable.task.push({
        sum: 0,
        yj: 0,               //佣金
        keyword: "",         //搜索关键词
        search1: 1,          //排序方式
        search2: 1,         //筛选方式
        value_added: ['1', 2],     //增值服务
        mold: 1,            //活动类型
        evaluate_content: {},//评价内容
        antistop: '',        //关键词淘口令
        coupon: '',     //优惠券淘口令
        coupon_money: '', //优惠券价格
        insurance: '',       //是否勾选保险
        insurancePrice: 0,     //保险价格
        evaluate_img: '',    // "多张图片用 ',' 逗号隔开 ，1,2,3",
        times: [{
          key: 7,
          value: '',
        }, {
          key: 8,
          value: '',
        }, {
          key: 9,
          value: '',
        }, {
          key: 10,
          value: '',
        }, {
          key: 11,
          value: '',
        }, {
          key: 12,
          value: '',
        }, {
          key: 13,
          value: '',
        }, {
          key: 14,
          value: '',
        }, {
          key: 15,
          value: '',
        }, {
          key: 16,
          value: '',
        }, {
          key: 17,
          value: '',
        }, {
          key: 18,
          value: '',
        }, {
          key: 19,
          value: '',
        }, {
          key: 20,
          value: '',
        }, {
          key: 21,
          value: '',
        }, {
          key: 22,
          value: '',
        }],
      })
      // this.
    },

    /* 删除数据 */
    isDelete(item) {
      var index = this.dataTable.task.indexOf(item)
      if (index !== -1) {
        this.dataTable.task.splice(index, 1)
      }
    },
    /**
     *
     * @param {File} file
     * 构造一个文件上传实例 return 一个Promise
     */
    uploadImgs(file) {
      return new Promise((resolve, reject) => {
        if (file) {
          var formData = new FormData()
          formData.append('file', file)
          uploadAct(formData).then(res => {
            resolve(res)
          })
        } else {
          resolve(null)
        }
      })
    },
    //添加评论
    addComment(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var promiss = this.$refs['fileUpload'].uploadFiles.map(item => {
            return this.uploadImgs(item.raw)
          })
          Promise.all(promiss)
            .then(results => {
              var fileIds = results.map(item => item.data.id).toString()
              addComment({
                ...this.commentData,
                evaluateImg: fileIds
              }).then(res => {
                if (res.code == 0) {
                  this.getList()
                  this.mulpArr = []
                  this.commentData.evaluateImg = ''
                  this.$message({
                    message: "添加评论成功",
                    type: 'success'
                  })

                } else {
                  this.$message({
                    message: res.msg,
                    type: 'error'
                  })
                }
              })
            })
            .catch(error => {
                this.$message.error(error)
            })
          return false
          // 提交图片 ==》sub
          if (this.$refs['fileUpload'].uploadFiles.length > 0) {
            this.$refs['fileUpload'].submit();
          } else {
            addComment(this.commentData).then(res => {
              if (res.code == 0) {
                this.getList()
                this.mulpArr = []
                this.commentData.evaluateImg = ''
                this.$message({
                  message: "添加评论成功",
                  type: 'success'
                })
              } else {
                this.$message({
                  message: res.msg,
                  type: 'error'
                })
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    //删除评论
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteComment({
          evaluateId: row.id,
        }).then(res => {
          this.getList()
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //确定上传，将id传给上去
    confirmUpload() {
      this.commentId = []
      this.getCommentList.forEach((item, index) => {
        if (item.state == true) {
          this.commentId.push(item.id)
        }
      })
      //查询图片总数
    getImg().then(res=>{
      if(res.code == 0){
          this.allImg = res.data.count
      }else{
         this.$message.error(res.msg)
      }
 })
      this.dataTable.evaluateIds = this.commentId.join()
      this.dialogFormVisible = false

    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    onerror(error, file, fileList) {
    },
    /* 点击上一步，下一步 */
    lastStep() {
      this.$router.push('selectpath')
    },
    nextStep() {
      this.dataTable.task.forEach(item => {
        item.times.forEach((value) => {
          if (value.value == '') {
            value.value = ''
          } else {
            value.value = Number(value.value)
          }
        })
      })

      if(this.removeList == '' && this.successList == ''){
        this.$message.warning('请上传图片')
        return false
   }
   if(this.removeList == '' && this.successList !== ''){
        this.dataTable.imgLink = this.successList
   }
      releaseAct(this.dataTable).then(res => {
        if (res.code !== 0) {
          if(res.msg == '请选择活动日期' && this.dataTable.taskTime != ''){
            this.$message.warning('时间日期不能为今天')
            return false
          }
          this.$message({
            message: res.msg,
            type: 'error'
          })
        } else {
          this.maskLayer = true
          this.buyPage = true
          this.goodsId = res.data.good_id
          verifyInfo({
            goodId: res.data.good_id
          }).then(res => {
            if (res.data.search1 == 1) {
              res.data.search1 = '综合'
            } else if (res.data.search1 == 2) {
              res.data.search1 = '销量'
            }
            res.data.task.forEach((item, index) => {
              if (item.mold == 1) {
                item.mold = '原价单'
              } else if (item.mold == 2) {
                item.mold = '评价单'
              } else {
                item.mold = '淘宝优惠券单'
              }
            })
            this.dataList = res.data
            this.allPrice = 0
            this.dataList.task.forEach((item, index) => {
              this.allPrice += parseInt(item.true_pay) + parseInt(item.store_commission) + parseInt(item.insurance_money)
            })
          })
        }
      }).catch(error => {
          this.$message.error(error)
      })
    },
    /* 确认支付，返回修改 */
    affirmPay() {
      goodsPay({goodsId:this.goodsId}).then(res=>{
          if(res.code == 0){
             this.$message.success('支付成功')
             setTimeout(()=>{
                this.$router.push('/activitylist')
             },1000)
          }else{
             this.$message.warning(res.msg)
          }
      })
    },
    /* 支付完成 */
    successTrue() {
      this.buySuccess = false
      this.maskLayer = false
    },
    /* 返回修改 */
    returnEdit() {
      this.buyPage = false
      this.maskLayer = false
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    /* 弹出框中table表格事件 */
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    },

  },
  created() {
    this.getList()
    //当shopsId为空的时候让其回到上个页面去拿那个shopsId
    if (this.$route.params.shopsId == undefined) {
      this.$router.push('selectpath')
    }
    //查询图片总数
    getImg().then(res=>{
         if(res.code == 0){
             this.allImg = res.data.count
         }else{
            this.$message.error(res.msg)
         }
    })
  }
}
